package com.example.erp;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

/**
 * @author jiang
 */
@RestController
@RequestMapping("/deepseek/client")
public class DeepSeekChatClientController {

	private static final String DEFAULT_PROMPT = "你好，介绍下你自己！";

	private final ChatClient deepSeekChatClient;

	public DeepSeekChatClientController(ChatModel chatModel) {
		this.deepSeekChatClient = ChatClient.builder(chatModel)
				.defaultAdvisors(MessageChatMemoryAdvisor.builder(MessageWindowChatMemory.builder().build()).build())
				// 实现 Logger 的 Advisor
				.defaultAdvisors(new SimpleLoggerAdvisor())
				// 设置 ChatClient 中 ChatModel 的 Options 参数
				.defaultOptions(OpenAiChatOptions.builder().temperature(0.7d).build()).build();
	}

	/**
	 * ChatClient 简单调用，执行默认提示语的 AI 生成请求
	 */
	@GetMapping("/simple/chat")
	public String chat() {
		return deepSeekChatClient.prompt(DEFAULT_PROMPT).call().content();
	}

	/**
	 * ChatClient 流式调用，调用流式生成接口 - 支持实时获取生成过程的分块响应
	 */
	@GetMapping("/stream/chat")
	public Flux<String> stream(HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		return deepSeekChatClient.prompt(DEFAULT_PROMPT).stream().content();
	}

	/**
	 * 使用自定义参数调用DeepSeek模型
	 *
	 * @return ChatResponse 包含模型响应结果的封装对象
	 * @apiNote 当前硬编码指定模型为deepseek-chat，温度参数0.7以平衡生成结果的创造性和稳定性
	 */
	@GetMapping(value = "/customOptions")
	public ChatResponse customOptions() {
		return this.deepSeekChatClient.prompt(new Prompt("Generate the names of 5 famous pirates.",
				OpenAiChatOptions.builder().temperature(0.75).build())).call().chatResponse();
	}
}